package com.lamda.zhekou.utils;

import java.sql.*;

/**
 * JDBC工具类型
 */
public class DBUtils {

    static {
        String driver = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param url      jdbc url
     * @param username 数据库用户名
     * @param password 数据库用户密码
     * @return 数据库密码
     */
    public static Connection getConn(String url, String username, String password) {
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    public static void close(Connection con, Statement stmt, ResultSet rs) {
        try {
            if (stmt != null) stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (con != null) con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (rs != null) rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection con, PreparedStatement stmt, ResultSet rs) {
        try {
            if (stmt != null) stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (con != null) con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (rs != null) rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行查询语句sql
     *
     * @param sql
     * @return
     */

    public static ResultSet getResultSet(Connection conn, String sql) {
        ResultSet rs = null;
        try {

            Statement stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return rs;
    }

    /**
     * 更新sql语句
     *
     * @param sql
     * @return 整数，更新的条数
     */

    public static int excuteUpdate(Connection conn, String sql) {
        int result = 0;
        try {
            result = conn.createStatement().executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * PreparedStatement的应用
     *
     * @param conn
     * @param sql
     * @return
     */
    public static PreparedStatement getPreparedStatement(Connection conn, String sql) {
        PreparedStatement ps = null;
        try {

            ps = conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ps;
    }

}